package uia.alumni.useradm;

import java.io.IOException;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;
import uia.alumni.data.Role;
import uia.alumni.data.User;
import uia.alumni.web.Command;



/**
 *
 * @author Even Åby Larsen (even.larsen@uia.no)
 */
public class SaveUserRoles extends Command implements Constants {
    /** SERVLET_NAME is used for consistency checking of web.xml */
    public static final String SERVLET_NAME = "admin.saveuserroles";

    @PersistenceUnit(name=PERSISTENCE_UNIT)
    private EntityManagerFactory emf;

    @Resource
    private UserTransaction tx;


    public SaveUserRoles() {
        super(Role.admin);
    }


    /** Save user data from the form created by EditUserRoles */
    public void execute(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        long uid = parseLong(request.getParameter(UID), -1);
        EntityManager em = emf.createEntityManager();

        try {
            tx.begin();
            User u = em.find(User.class, uid);
            if (u == null) throw new Exception("No user!");

            for (Role r : Role.values()) {
                if (request.getParameter(r.name()) != null) {
                    u.addRole(r);
                }
                else {
                    u.removeRole(r);
                }
            }
            tx.commit();
        }
        catch (Exception e) {
            addMessage(request, "Save roles failed, because: "+e.getMessage());
        }
        forwardTo(UserAdmin.SERVLET_NAME, request, response);
    }

    
    public final static long serialVersionUID = 1;
}
